package com.java.netty.nio.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author: Dgg
 * @Date: 2021/12/28 22:43
 */
public class GroupChatServer {

	private int port;

	public GroupChatServer(int port) {
		this.port = port;
	}


	//编写run 方法处理客户端请求
	public void run() throws InterruptedException {
		EventLoopGroup boosGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup(8);
		try {
			//创建两个线程组
			ServerBootstrap b = new ServerBootstrap();

			b.group(boosGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 128)
					.childOption(ChannelOption.SO_KEEPALIVE, true)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {

							//获取到pipeline
							ChannelPipeline pipeline = ch.pipeline();
							//向pipeline 里面增加 解码器 其实是个handler
							pipeline.addLast("decoder", new StringDecoder());
							//向pipeline 里面增加 编码器 其实是个handler
							pipeline.addLast("encoder", new StringEncoder());

							//加入自己的业务处理handler
							pipeline.addLast(new GroupChatServerHandler());

						}
					});
			System.out.println("netty 服务器启动");
			ChannelFuture channelFuture = b.bind(port).sync();

			//监听关闭事件
			channelFuture.channel().closeFuture().sync();
		} finally {
			boosGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws InterruptedException {

		GroupChatServer groupChatServer = new GroupChatServer(6667);
		groupChatServer.run();

	}
}
